package com.example.rpcdemo.rpc.codec;

import com.example.rpcdemo.rpc.RpcRequest;
import com.example.rpcdemo.rpc.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    
    private Class<?> genericClass;
    
    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }
    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        
        in.markReaderIndex();
        int dataLength = in.readInt();
        
        if (dataLength < 0) {
            ctx.close();
        }
        
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
        Object obj = ois.readObject();
        ois.close();
        
        out.add(obj);
    }
}